# -*- coding: utf8 -*-
import numpy as np
import os
from PIL import Image
from sklearn.externals import joblib
from sklearn.neighbors import KNeighborsClassifier


def load_dataset():
    X = []
    y = []
    for i in "2345678abcdefgmnpwxy":
        target_path = "split_image1000/" + str(i)
        for title in os.listdir(target_path):
            pix = np.asarray(Image.open(os.path.join(target_path, title)).convert('L'))
            X.append(pix.reshape(25 * 50))
            y.append(target_path.split('/')[-1])
    X = np.asarray(X)
    y = np.asarray(y)
    return X, y

def check_everyone(model):
    pre_list = []
    y_list = []
    for i in "2345678abcdefgmnpwxy":
        part_path = "split_image1000/"+ str(i)
        for title in os.listdir(part_path):
            pix = np.asarray(Image.open(os.path.join(part_path, title)).convert('L'))
            pix = pix.reshape(25 * 50)
            pre_list.append(pix)
            y_list.append(part_path.split('/')[-1])
    pre_list = np.asarray(pre_list)
    y_list = np.asarray(y_list)
    result_list = model.predict(pre_list)
    res = list(result_list == y_list)
    print('样本数: {}\n预测成功率: {}'.format(len(res), float(res.count(True)) / len(res)))


print('正在加载数据……')
X, y = load_dataset()
print('开始训练数据……')
knn = KNeighborsClassifier()
knn.fit(X, y)
print('生成训练模型……')
joblib.dump(knn, 'authcode_py2.model',protocol=2)
print('进行模型验证……')
check_everyone(knn)
